package com.yanhua.transaction.netty;

import com.alibaba.fastjson.JSON;
import com.yanhua.transaction.common.dto.TransactionGroupDto;
import com.yanhua.transaction.common.util.TransactionConst;
import com.yanhua.transaction.transactional.YhTransaction;
import com.yanhua.transaction.transactional.YhTransactionManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Objects;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private ChannelHandlerContext context;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接受数据:" + msg.toString());
        TransactionGroupDto transactionGroupDto = JSON.parseObject(msg.toString(), TransactionGroupDto.class);

        String groupId = transactionGroupDto.getGroupId();
        TransactionConst.TransactionType transactionType = transactionGroupDto.getTransactionType();

        System.out.println("接收command:" + transactionType);
        // 对事务进行操作


        YhTransaction yhTransaction = YhTransactionManager.getLbTransaction(groupId);
        if (Objects.equals(transactionType, TransactionConst.TransactionType.rollback)) {
            yhTransaction.setTransactionType(TransactionConst.TransactionType.rollback);
        } else if (Objects.equals(transactionType, TransactionConst.TransactionType.commit)) {
            yhTransaction.setTransactionType(TransactionConst.TransactionType.commit);
        }
        yhTransaction.getTask().signalTask();
    }

    public synchronized Object call(String msg) throws Exception {
        context.writeAndFlush(msg);
        return null;
    }
}
